package com.sjs.flow.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.sjs.flow.entity.BaseEntity;
import com.sjs.flow.utils.EntityUtil;
import com.sjs.flow.utils.FlowIdUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

/**
 * @author uto_dev_008
 * @desc
 * @since 2021/11/24 10:51
 * Copyright (c) 2021 南京友拓信息技术有限公司 All rights reserved
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        //根据属性名字设置要填充的值
        Object obj = metaObject.getOriginalObject();
        if (obj instanceof BaseEntity) {
            Object object = metaObject.getValue("id");
            Object createTime = metaObject.getValue("createTime");
            Object updateTime = metaObject.getValue("updateTime");
            Object updateId = metaObject.getValue("updateId");
            Object createId = metaObject.getValue("createId");
            if ((object == null) || (object.toString().trim().equals(""))) {
                this.setFieldValByName("id", FlowIdUtil.getSnowId(), metaObject);
            }
            if (createTime == null) {
                this.setFieldValByName("createTime", EntityUtil.getSystemDate(), metaObject);
            }
            if (updateTime == null) {
                this.setFieldValByName("updateTime", EntityUtil.getSystemDate(), metaObject);
            }
            if (updateId == null) {
                this.setFieldValByName("updateId", EntityUtil.getUserId(), metaObject);
            }
            if (createId == null) {
                this.setFieldValByName("createId", EntityUtil.getUserId(), metaObject);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Object updateTime = metaObject.getValue("updateTime");
        Object updateId = metaObject.getValue("updateId");
        if (updateTime == null) {
            this.setFieldValByName("updateTime", EntityUtil.getSystemDate(), metaObject);
        }
        if (updateId == null) {
            this.setFieldValByName("updateId", EntityUtil.getUserId(), metaObject);
        }
    }
}
